<template>
  <up-picker
      ref="pickerRef"
      :columns="columns"
      :show="isShow"
      close-on-click-overlay
      key-name="shop_name"
      @cancel="handleCancel"
      @change="handleChange"
      @close="handleClose"
      @confirm="handleConfirm"
  />
</template>
<script lang="ts" setup>
import {ref} from "vue"
import {getShops} from "@/api/shop"
import type ShopResponse from "@/api/types/ShopResponse";

const shopId = defineModel<number>("shopId")
const shopName = defineModel<string>("shopName")
const isShow = defineModel<boolean>("show")
const columns = ref<ShopResponse[][]>([])
const shops = ref<ShopResponse[]>()
const pickerRef = ref<UniPickerRef>()

async function getData() {
  const {data} = await getShops()
  if (data.result !== undefined) {
    shops.value = data.result
    columns.value.push(shops.value.map(shopResponse => removeShopResponseChildren(shopResponse)))
    if (shops.value[0].childs !== undefined) {
      columns.value.push(shops.value[0].childs.map(shopResponse => removeShopResponseChildren(shopResponse)))
    }
  }
}

getData()

function closePicker() {
  isShow.value = false
}

function handleCancel() {
  closePicker()
}

function handleClose() {
  closePicker()
}

function handleConfirm({value}: { value: ShopResponse[] }) {
  shopId.value = value[value.length - 1].selfid
  shopName.value = value[value.length - 1].shop_name
  closePicker()
}

function handleChange({columnIndex, index}: { columnIndex: number, index: number }) {
  if (columnIndex === 0) {
    pickerRef.value?.setColumnValues(1, shops.value?.[index].childs?.map(shopResponse => removeShopResponseChildren(shopResponse)))
  }
}

function removeShopResponseChildren(shopResponse: ShopResponse) {
  const newShopResponse: ShopResponse = {...shopResponse}
  delete newShopResponse.childs
  return newShopResponse
}
</script>
